package com.coder.rental.utils;

import com.coder.rental.entity.Dept;
import com.coder.rental.entity.Permission;
import com.coder.rental.vo.RouteVo;
import org.springframework.beans.BeanUtils;

import java.util.ArrayList;
import java.util.List;
import java.util.Optional;

/**
 * 路由树工具类
 */
public class RouteTreeUtil {
    public static List<RouteVo> buildRouteTree(List<Permission>permissionList,int pid){
        List<RouteVo> routeVoList = new ArrayList<>();
        Optional.ofNullable(permissionList).orElse(new ArrayList<>())
                .stream()
                .filter(permission -> permission!=null && permission.getPid()==pid)
                .forEach(permission -> {
                    RouteVo routeVo = new RouteVo();
                    routeVo.setPath(permission.getRoutePath()); // 获取路由地址
                    routeVo.setName(permission.getRouteName()); // 获取路由名称
                    // pid 为0时，表示是根目录，设置alwaysShow为true，表示一直显示，如果非0,则设置component为子目录的url
                    // pid是数据库设置的父级id，如果为0，则为根目录，如果为1，则为子目录，如果为2，则为按钮级别
                    if(permission.getPid()==0){
                       routeVo.setComponent("Layout");
                       routeVo.setAlwaysShow(true);
                    }else {
                        routeVo.setComponent(permission.getRouteUrl());
                        routeVo.setAlwaysShow(false);
                    }
                    // 设置meta信息，包含权限名称、图标、权限标识
                    routeVo.setMeta(routeVo.new Meta(permission.getPermissionLabel(),
                            permission.getIcon(),
                            permission.getPermissionCode().split(",")));

                    // 递归获取子目录,构建路由树
                    List<RouteVo> children = buildRouteTree(permissionList,permission.getId());
                    routeVo.setChildren(children);
                    routeVoList.add(routeVo);
                });
        return routeVoList;
    }

    public static List<Permission> buildMenuTree(List<Permission> permissionList, int pid){
        List<Permission> permissionTree = new ArrayList<>();
        Optional.ofNullable(permissionList).orElse(new ArrayList<>())
                .stream().filter(permission -> permission!=null && permission.getPid() == pid)
                .forEach(permission -> {
                    Permission menu = new Permission();
                    BeanUtils.copyProperties(permission, menu);
                    menu.setChildren(buildMenuTree(permissionList, permission.getId()));
                    permissionTree.add(menu);
                });
        return permissionTree;
    }
}
